package common

import (
	"fmt"
	"gopkg.in/yaml.v3"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"strings"
)

//type fscanGo struct{
//	profiles profiles `yaml:"profiles"`
//}
//
//type profiles struct {
//	active string `yaml:"active"`
//}

type ConfigYml struct {
	//fscanGo *fscanGo `yaml:"fscango"`
	Active     string     `yaml:"active"`
	Url        string     `yaml:"url"`
	PostUrl    string     `yaml:"postUrl"`
	Cron       string     `yaml:"cron"`
	RedisCache *RedisRing `yaml:"redis_result"`
}

func LoadConfigYml(appDir string) (*ConfigYml, error) {
	//操作系统指定的路径分隔符
	separator := string(os.PathSeparator)
	if strings.Compare(appDir, "") == 0 {
		pwddir, err := os.Getwd()
		if err != nil {
			fmt.Println(err)
			return nil, err
		}
		appDir = path.Dir(pwddir) + separator + "app"
	}
	//fmt.Println("app所在路径：", appDir)
	absDir, err := filepath.Abs(appDir)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	dir, err := os.OpenFile(absDir, os.O_RDONLY, os.ModeDir)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	//延迟关闭目录
	defer dir.Close()
	fileInfos, _ := dir.ReadDir(-1)
	defaultApplicationFileName := "application.yml"
	fullfilename := absDir + separator + defaultApplicationFileName

	yamlFile, err := ioutil.ReadFile(fullfilename)
	if err != nil {
		fmt.Println(fullfilename, err)
		return nil, err
	}
	cfg := &ConfigYml{}

	err = yaml.Unmarshal(yamlFile, cfg)
	if err != nil {
		fmt.Println(fullfilename, err)
		return nil, err
	}
	env := cfg.Active
	//fmt.Println("当前激活的配置文件是：", env)
	if strings.Compare(env, "") == 0 {
		fmt.Println("请检查文件内容是否按要求", fullfilename)
		return nil, err
	}
	for _, f := range fileInfos {
		if f.IsDir() {
			envYmlFile := filepath.Join(absDir, f.Name(), env+".yml")
			yamlFile, err := ioutil.ReadFile(envYmlFile)
			if err != nil {
				fmt.Println(envYmlFile, err)
				continue
			}
			err = yaml.Unmarshal(yamlFile, cfg)
			if err != nil {
				fmt.Println(envYmlFile, err)
				continue
			}
		}
	}
	return cfg, nil
}
